package com.wuhao.code.check.model

import com.aegis.mybatis.xmlless.model.base.BaseSimpleClassWrapper
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiClassReferenceType
import com.wuhao.code.check.model.base.BasePsiFieldWrapper
import org.jetbrains.kotlin.psi.KtCallableDeclaration

/**
 *
 * @author 吴昊
 * @date 2024/1/19 12:08
 * @since v0.0.0
 * @version 1.0
 */
class PsiTableFieldWrapper(private val field: PsiField) : BasePsiFieldWrapper(field) {


  override fun getFieldType(): BaseSimpleClassWrapper {
    val ref = field.getTypeClass()
    if (ref != null) {
      return SimplePsiClassWrapper(ref)
    }
    throw RuntimeException("无法获取字段类型")
  }

  override fun getFieldName(): String {
    return field.name
  }

  override fun isCharSequence(): Boolean {
    return if (field is KtCallableDeclaration) {
      field.typeReference?.text in listOf("String", "String?")
    } else {
      false
    }
  }

}

fun PsiVariable.getTypeClass(): PsiClass? {
  val type = this.type
  return getClassOfType(type)
}

private fun PsiVariable.getClassOfType(type: PsiType): PsiClass? {
  when (type) {
    is PsiClassReferenceType -> {
      val resolve = type.resolve()
      if (resolve is PsiClass) {
        return resolve
      }
    }

    is PsiPrimitiveType      -> {
      val realType = type.getBoxedType(this)?.resolve()
      if (realType is PsiClass) {
        return realType
      }
    }

    is PsiArrayType          -> {
      return getClassOfType(type.componentType)
    }
  }
  return null
}
